package com.calvin.study.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

//自定义Realm完成认证和授权
public class CustomerMD5Realm extends AuthorizingRealm {

	//授权
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		//System.out.println("授权");
		String primaryPrincipal = (String) principals.getPrimaryPrincipal();
		
		SimpleAuthorizationInfo simpleAuthorizationInfo = new  SimpleAuthorizationInfo();
		simpleAuthorizationInfo.addRole("admin");
		simpleAuthorizationInfo.addRole("user");
		
		simpleAuthorizationInfo.addStringPermission("user:*:01");
		simpleAuthorizationInfo.addStringPermission("prodect:*");
		
		return simpleAuthorizationInfo;
	}

	//认证
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		//System.out.println("认证");
		//标识用户身份的唯一凭证 可以是用户名、手机号、证件号…必须是唯一的
		String username = (String) token.getPrincipal();
		
		//模拟从数据库查询用户名密码信息
		if("admin".equals(username)) {
			SimpleAuthenticationInfo authInfo = new SimpleAuthenticationInfo(
					username, 
					"F08A223218D0D2E68AC3A6CE4154851E",
					ByteSource.Util.bytes("bQV8afqTIhue0pZ70s4pd355WryxZVmN"),
					this.getName());
			return authInfo;
		}
		return null;
	}

}
